/**
 *  julive
 *
 *  Create by songli on 2021/07/07
 *  Copyright © 2021 居理买房网. All rights reserved.
 */

package service

import (
	"context"
	"fmt"

	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"

	"git.julive.com/julive/shorturl/server/domain"
	"git.julive.com/julive/shorturl/server/proto/shorturl"
)

type ShorturlService struct {
	shorturl.UnimplementedShorturlServiceServer

	dm domain.ShorturlDomain
}

func NewShorturlService() *ShorturlService {
	dm := domain.NewShorturlDomain()
	svc := &ShorturlService{
		dm: dm,
	}

	return svc
}

// CreateShorturl 创建Shorturl
func (svc *ShorturlService) CreateShorturl(ctx context.Context, req *shorturl.CreateShorturlRequest) (*shorturl.CreateShorturlResponse, error) {
	rsp := &shorturl.CreateShorturlResponse{}
	path := req.Path
	if len(path) == 0 {
		rsp.ErrMsg = "path不能为空"
		rsp.Code = 1002
		return rsp, nil
	}

	url := req.Url
	if len(url) == 0 {
		rsp.ErrMsg = "url不能为空"
		rsp.Code = 1002
		return rsp, nil
	}

	m, err := svc.dm.CreateShorturl(ctx, path, url)
	if err != nil {
		rsp.ErrMsg = "创建Shorturl失败"
		rsp.Code = 1007
		return rsp, nil
	}
	rsp.Data = m
	return rsp, nil
}

// GetShorturlById 根据Id获取Shorturl
func (svc *ShorturlService) GetLongurl(ctx context.Context, req *shorturl.GetLongurlRequest) (*shorturl.GetLongurlResponse, error) {
	fmt.Println("Received GetShorturl request", req.Path, req.Url)
	rsp := &shorturl.GetLongurlResponse{}
	m, err := svc.dm.GetLongurl(ctx, req.Path, req.Url)
	if err != nil || m == nil {
		rsp.ErrMsg = "获取Shorturl失败"
		rsp.Code = 1007
		return rsp, nil
	}

	url := m.Longurl

	header := metadata.Pairs("Location", url)
	grpc.SendHeader(ctx, header)

	return rsp, nil
}
